﻿import ko = require("knockout");
import Classes = require("classes");
import Project = require("Project");
import Clip = require("Clip");

class Track implements Classes.ITrack {
    public constructor(public project: Project, public track: EditoneLibRT.Track) {
        track.addEventListener("propertychanged", (prop: string) => this.onPropertyChanged(prop));
        this.refreshClips();
        
        this.name.subscribe((val) => { this.track.name = val; });
        this.color.subscribe((val) => { this.track.color = val; });
        this.volume.subscribe((val) => { this.track.volume = val; });
        this.balance.subscribe((val) => { this.track.balance = val; });
        this.height.subscribe((val) => { this.track.height = val; });
        this.clips.subscribe((val) => { /*todo*/ });
    }

    isAudioTrack : boolean = this.track.isAudioTrack;

    numChannels : number = this.track.numChannels;

    guid: string = this.track.guid;

    type: string = this.track.type;

    clips: KnockoutObservableArray<{clip: Clip, offset: number}> = ko.observableArray([]);

    name: KnockoutObservable<string> = ko.observable(this.track.name);

    color: KnockoutObservable<string> = ko.observable(this.track.color);

    volume: KnockoutObservable<number> = ko.observable(this.isAudioTrack ? this.track.volume: null);

    balance: KnockoutObservable<number> = ko.observable(this.isAudioTrack && this.numChannels == 2 ? this.track.balance : null);

    height: KnockoutObservable<number> = ko.observable(this.track.height);

    themeClass: KnockoutComputed<string> = ko.computed(() => { return 'theme-' + this.color().toLowerCase(); });

    delete: ()=>void =  () => {
        this.track.delete();
    }

    private refreshClips(): void {
        if (this.track.clips === null) {
            this.clips([]);
            return;
        }

        var clips: { clip: Clip, offset: number }[] = [];
        var it = this.track.clips.first();
        var i = 0;
        while (it.hasCurrent) {
            clips[i] = { clip: new Clip(it.current.value), offset: it.current.key };
            i++;
            it.moveNext();
        }

        this.clips(clips);
    }

    onPropertyChanged(prop: string): void {
        prop = prop.charAt(0).toLowerCase() + prop.slice(1);
        if (prop in this) {
            if (prop == "clips") {
                this.refreshClips();
            } else {
                this[prop](this.track[prop]);
            }
        }
    }
}

export = Track